#include <head.h>

struct sockaddr_in addrArr[3000];
int count = 0;

uint32_t stringIPtoNum(char *pIP)
{
    uint32_t nIP = 0;
    // AF_INET是代表IPV4地址的意思，AF_INET6代表IPV6
    inet_pton(AF_INET, pIP, &nIP);
    return nIP;
}

// 把数字IP转为字符串IP
void numIPtoString(uint32_t ip, char *psIP, int size)
{
    inet_ntop(AF_INET, &ip, psIP, size);
}

int main(int argc, char const *argv[])
{
    int val = 1;

    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (-1 == fd)
    {
        perror("socket");
    }
    struct sockaddr_in addr;
    addr.sin_addr.s_addr = stringIPtoNum("192.168.70.37");
    addr.sin_port = htons(8888);
    addr.sin_family = AF_INET;

    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));

    if (-1 == bind(fd, (struct sockaddr *)&addr, sizeof(addr)))
    {
        perror("bind");
    }
    
    

    while (1)
    {
        char buf[1024];
        struct sockaddr_in clientAddr;
        socklen_t len = sizeof(clientAddr);
        recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *)&clientAddr, &len);
        if (strcmp (buf, "baodao")==0)
        {
            addrArr[count]=clientAddr;
            count++;
            char psIP[16];
            numIPtoString(clientAddr.sin_addr.s_addr, psIP, sizeof(psIP));
            printf("收到一个报到消息，已经把它的地址存入数组中，后续可以遍历数组给它发消息");
            printf("这个地址的ip为：%s,端口为：%d\n",psIP,htons(clientAddr.sin_port));
           
        }else{
            
            printf("%s\n", buf);
        }
        
       
        
    }

    return 0;
}